<template>
  <div class="app-container">
    <div
      style="
        width: 100%;
        height: 5%;
        padding-left: 20px;
        padding-top: 20px;
        padding-bottom: 30px;
      "
    >
      <breadcrumb :naviItems.sync="naviItems"></breadcrumb>
    </div>
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建
      </el-button>
      <el-button
        class="filter-item"
        type="danger"
        icon="el-icon-remove"
        @click="handleRemove"
      >
        删除
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 15px"
        type="info"
        icon="el-icon-refresh"
        @click="handleRefresh"
      >
        刷新
      </el-button>
    </div>
    <el-table
      ref="multipleTable"
      :data="list"
      row-key="id"
      stripe
      border
      tooltip-effect="light"
      style="width: 100%"
      :tree-props="{ children: 'children' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column v-if="false" align="center" prop="id" label="id" />
      <el-table-column label="序号" type="index" width="55" align="center">
        <template slot-scope="scope">
          <span>{{
            (listQuery.current - 1) * listQuery.size + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="name"
        label="名称"
        sortable
        width="140"
      />
      <el-table-column
        align="center"
        prop="poolName"
        label="数据源"
        width="250"
      />
      <el-table-column
        align="center"
        prop="integratedName"
        label="集成数据库"
        width="250"
      />
      <el-table-column align="center" prop="testPeriod" label="测试周期" />
      <el-table-column align="center" prop="runTime" label="执行时间" />
      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            @click="handleClick(scope.row, false)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="mini"
            @click="handleClick(scope.row, true, false)"
            >编辑</el-button
          >
          <el-button type="text" size="mini" @click="handleDetail(scope.row)"
            >配置</el-button
          >
          <el-button type="text" size="mini" @click="handleRun(scope.row)"
            >运行</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleRemove(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      :title.sync="dialogTitle"
      :visible.sync="dialogVisible"
      width="70%"
      align="center"
      :before-close="handleClose"
    >
      <el-container style="width: 60%">
        <el-form
          ref="item"
          :rules="rules"
          style="width: 100%"
          label-position="left"
          label-width="20%"
          :model="item"
        >
          <el-form-item v-show="false" label="id">
            <el-input v-model="item.id" />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="item.name" :disabled="!dialogEdit" />
          </el-form-item>
          <el-form-item label="数据源" prop="dbpoolId">
            <el-select
              v-model="item.dbpoolId"
              :disabled="!dialogEdit || !dislogEditItem"
              style="width: 100%"
              placeholder="请选择数据源"
              @change="poolHandleChange"
            >
              <el-option
                v-for="cur in sourceList"
                :key="cur.id"
                :label="cur.poolName"
                :value="cur.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="集成数据库" prop="tables">
            <el-select
              v-model="item.tables"
              :disabled="!dialogEdit || !dislogEditItem"
              multiple
              style="width: 100%"
              placeholder="请先选择数据源"
              @change="integratedNameHandleChange"
            >
              <el-option
                v-for="cur in inteSourceList"
                :key="cur"
                :label="cur"
                :value="cur"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="集成名称" prop="integratedName">
            <el-input
              v-model="item.integratedName"
              :disabled="!dialogEdit"
              placeholder="仅允许数字、字母、下划线"
            />
          </el-form-item>
          <el-form-item label="测试周期">
            <el-input
              v-model="item.testPeriod"
              :disabled="!dialogEdit"
              placeholder="例如：每月/每周/每天"
            />
          </el-form-item>
          <el-form-item label="执行时间">
            <el-input
              v-model="item.runTime"
              :disabled="!dialogEdit"
              placeholder="例如：每月1日 8:00 / 每周一 8:00 / 每天 8:00"
            />
          </el-form-item>
        </el-form>
      </el-container>
      <span v-if="dialogEdit" slot="footer" class="dialog-footer">
        <el-button @click="handleRefreshRule('item')">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('item')"
          >确 定</el-button
        >
      </span>
      <span v-else slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  page,
  addOrUpdate,
  removes,
  integratePool,
  getInfo,
  run,
} from "@/api/integrate";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { list } from "@/api/pool";
import Breadcrumb from "../../components/QipingBreadCrumb/BreadCrumb.vue";
import { mapGetters } from "vuex";
export default {
  name: "Integrate",
  components: { Pagination, Breadcrumb },
  computed: {
    naviItems() {
      return [
        { text: this.equTypeName },
        { text: "数据测试" },
        { text: "集成测试" },
        { text: "测试列表" },
      ];
    },
    ...mapGetters(["equTypeName"]),
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("集成名不能为空"));
      } else if (!/^[0-9a-zA-Z_]{1,}$/.test(value)) {
        callback(new Error("请输入正确格式的集成名"));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      listLoading: true,
      selectionItem: [],
      dialogVisible: false,
      dialogRunVisible: false,
      dialogTitle: "新增数据集成测评",
      dialogEdit: true,
      dislogEditItem: true,
      item: {},
      listQuery: {
        current: 1,
        size: 20,
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        tables: [
          {
            required: true,
            message: "请选择集成数据库",
            trigger: "blur",
          },
        ],
        dbpoolId: [
          {
            required: true,
            message: "请选择数据源",
            trigger: "blur",
          },
        ],
        integratedName: [
          {
            required: true,
            message: "请选择数据源",
            trigger: "blur",
          },
          {
            required: true,
            validator: validateName,
            message: "仅支持数字、字母、下划线",
            trigger: "blur",
          },
        ],
      },
      list: [],
      tableData: [],
      sourceList: [],
      inteSourceList: [],
      backList: "",
    };
  },

  created() {
    this.getList();
    list().then((res) => {
      this.sourceList = res.data;
    });
  },

  methods: {
    /**
     * 运行
     */
    handleRun(row) {
      this.listLoading = true;
      this.dialogRunVisible = true;
      run(row.id).then((res) => {
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
          this.$message({
            message: "运行成功！",
            type: "success",
          });
        }, 2 * 1000);
      });
    },
    /**
     * 查看详情
     */
    handleDetail(row) {
      console.log(row.id)
      this.$router.replace({
        name: "reload",
        params: {
          to: "/qzjdataTest/integrate/detail/" + row.id,
        },
      });
      // this.$router.push({ path: "/integrate/detail/" + row.id });
    },
    /**
     * 数据源改变
     */
    poolHandleChange(val) {
      if (val) {
        this.inteSourceList = [];
        integratePool({ id: val }).then((res) => {
          this.inteSourceList = res.data;
        });
      }
    },

    integratedNameHandleChange(val) {
      this.item.tables = val;
    },

    getList() {
      this.listLoading = true;
      page(this.listQuery).then((response) => {
        this.total = response.data.total;
        this.list = response.data.records;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 1.5 * 1000);
      });
    },

    /**
     * 单行编辑
     * @param row
     */
    handleClick(row, isEdit, isPool) {
      getInfo(row.id).then((res) => {
        // console.log(res)
        this.item = res.data;
      });
      this.backList = JSON.stringify(this.list);
      this.dialogVisible = true;
      this.dialogTitle = row.name;
      this.dialogEdit = isEdit;
      this.dislogEditItem = isPool;
      this.inteSourceList = [];
    },

    /**
     * 添加
     */
    handleCreate() {
      this.dialogVisible = true;
      this.dialogTitle = "新增数据集成测评";
      this.item = {};
      this.dialogEdit = true;
      this.dislogEditItem = true;
      this.inteSourceList = [];
    },

    /**
     * 删除
     */
    handleRemove(index, row) {
      const data = [];
      if (row) {
        data.push(`${row.id}`);
      } else {
        if (this.selectionItem.length < 1) return;
        this.selectionItem.forEach((item) => {
          data.push(`${item.id}`);
        });
      }
      removes({ ids: data.join(",") }).then((response) => {
        this.getList();
      });
    },

    /**
     * 刷新
     */
    handleRefresh() {
      this.getList();
    },

    /**
     * 多选行
     * @param rows
     */
    handleSelectionChange(rows) {
      this.selectionItem = rows;
    },

    /**
     * dialog关闭
     * @param done
     */
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          // done();
          this.dialogVisible = false;
          this.list = JSON.parse(this.backList);
        })
        .catch((_) => {});
    },

    handleRunClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          // done();
          this.dialogRunVisible = false;
          this.tableData = JSON.parse(this.backList);
        })
        .catch((_) => {});
    },

    handleConfirm(formName) {
      this.listLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addOrUpdate(this.item)
            .then()
            .then((response) => {
              this.dialogVisible = false;
              this.getList();

              // Just to simulate the time of the request
              setTimeout(() => {
                this.listLoading = false;
              }, 1.5 * 1000);
            });
        } else {
          return false;
        }
      });
    },

    handleRefreshRule(formName) {
      this.dialogVisible = false;
      this.list = JSON.parse(this.backList);
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
</style>
